package com.edou.base.util;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 图片操作类 - 部分功能已废弃
 * 已有新版本 ，请参考ImageIm4Util
 * @author admin
 *
 */
public class ImageUtil {
	
	private static Log logger = LogFactory.getLog(ImageUtil.class);
	
	private static int width;
    private static int height;
    private static int scaleWidth;
    private static double  support = (double) 3.0;
    private static double PI = (double) 3.14159265358978;
    private static double[] contrib;
    private static double[] normContrib;
    private static double[] tmpContrib;
    //private static int startContrib, stopContrib;
    private static int nDots;
    private static int nHalfDots;
    
	/**
     * 裁剪图片
     * @param src
     * @param dest
     * @param x
     * @param y
     * @param w
     * @param h
     * @throws IOException
     */
	@SuppressWarnings("rawtypes")
	public static void cutImage(String src,String dest,int x,int y,int w,int h,String fileExt) throws IOException {   
        Iterator iterator = ImageIO.getImageReadersByFormatName(fileExt);   
        ImageReader reader = (ImageReader)iterator.next();   
        InputStream in=new FileInputStream(src);  
        ImageInputStream iis = ImageIO.createImageInputStream(in);   
        reader.setInput(iis, true);   
        ImageReadParam param = reader.getDefaultReadParam();   
        Rectangle rect = new Rectangle(x, y, w,h);    
        param.setSourceRegion(rect);   
        BufferedImage bi = reader.read(0,param);     
        ImageIO.write(bi, fileExt, new File(dest));  
    }
	
    /** 
     * 图片缩放 
     */  
    @SuppressWarnings("static-access")
	public static void zoomImage(String src,String dest,int w,int h) throws Exception {  
        double wr=0,hr=0;  
        File srcFile = new File(src);  
        File destFile = new File(dest);  
        BufferedImage bufImg = ImageIO.read(srcFile);  
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);  
        wr=w*1.0/bufImg.getWidth();  
        hr=h*1.0 / bufImg.getHeight();  
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);  
        Itemp = ato.filter(bufImg, null);  
        try {  
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
          
    }
    
    /**
     * 得到图片的宽高
     * @param src
     * @return
     * @throws IOException
     */
    public static int[] getImageWAndH(String src) throws IOException{
    	File srcFile = new File(src);  
    	BufferedImage bufImg = ImageIO.read(srcFile);
    	return new int[]{bufImg.getWidth(),bufImg.getHeight()};
    }
    
   /**
    * 小图生成在同路径下
    * @param fromFileStr 原图片地址
    * @param formatWideth 生成图片宽度
    * @param formatHeight 生成图片高度
    */
   public static void resizeImage(String fromFileStr,
           int formatWideth, int formatHeight) {
       BufferedImage srcImage;
       File fromFile = new File(fromFileStr);
       String fileSuffix = fromFile.getName().substring((fromFile.getName().indexOf(".") + 1),(fromFile.getName().length()));  
       String newFilePath = fromFile.getPath().substring(0,(fromFile.getPath().lastIndexOf(".")))+ "_s" + "." + fileSuffix;
       File saveFile = new File(newFilePath);
       try {
       	srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
           int imageWideth = srcImage.getWidth(null);
           int imageHeight = srcImage.getHeight(null);
           int changeToWideth = 0;
           int changeToHeight = 0;
           if (imageWideth > 0 && imageHeight > 0) {
               // flag=true;
               if (imageWideth / imageHeight >= formatWideth / formatHeight) {
                   if (imageWideth > formatWideth) {
                       changeToWideth = formatWideth;
                       changeToHeight = (imageHeight * formatWideth) / imageWideth;
                   } else {
                       changeToWideth = imageWideth;
                       changeToHeight = imageHeight;
                   }
               } else {
                   if (imageHeight > formatHeight) {
                       changeToHeight = formatHeight;
                       changeToWideth = (imageWideth * formatHeight) / imageHeight;
                   } else {
                       changeToWideth = imageWideth;
                       changeToHeight = imageHeight;
                   }
               }
           }

           srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight);
           ImageIO.write(srcImage, "JPEG", saveFile);
           System.out.println("生成图片成功:"+newFilePath);  
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			System.out.println("生成图片成功:"+newFilePath);  
		}
       
   }
   /**
    * 生成固定大小的图片 500,331
    * @param path
    */
   public static void resizeImage(String path){
   	 ImageUtil.resizeImage(path,500, 331);
   }
   
   public static BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
       width = srcBufferImage.getWidth();
       height = srcBufferImage.getHeight();
       scaleWidth = w;
       if (DetermineResultSize(w, h) == 1) {
           return srcBufferImage;
       }
       CalContrib();
       BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
       BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
       return pbFinalOut;
   }

 
   private static  int DetermineResultSize(int w, int h) {
       double scaleH, scaleV;
       scaleH = (double) w / (double) width;
       scaleV = (double) h / (double) height;
       // 需要判断一下scaleH，scaleV，不做放大操作
       if (scaleH >= 1.0 && scaleV >= 1.0) {
           return 1;
       }
       return 0;

   } // end of DetermineResultSize()

   private static double Lanczos(int i, int inWidth, int outWidth, double Support) {
       double x;

       x = (double) i * (double) outWidth / (double) inWidth;

       return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
               / (x * PI / Support);

   }

   private static void CalContrib() {
       nHalfDots = (int) ((double) width * support / (double) scaleWidth);
       nDots = nHalfDots * 2 + 1;
       try {
           contrib = new double[nDots];
           normContrib = new double[nDots];
           tmpContrib = new double[nDots];
       } catch (Exception e) {
    	   	   logger.error(e.getMessage(),e);
           System.out.println("init   contrib,normContrib,tmpContrib" + e);
       }

       int center = nHalfDots;
       contrib[center] = 1.0;

       double weight = 0.0;
       int i = 0;
       for (i = 1; i <= center; i++) {
           contrib[center + i] = Lanczos(i, width, scaleWidth, support);
           weight += contrib[center + i];
       }

       for (i = center - 1; i >= 0; i--) {
           contrib[i] = contrib[center * 2 - i];
       }

       weight = weight * 2 + 1.0;

       for (i = 0; i <= center; i++) {
           normContrib[i] = contrib[i] / weight;
       }

       for (i = center + 1; i < nDots; i++) {
           normContrib[i] = normContrib[center * 2 - i];
       }
   } // end of CalContrib()

   // 处理边缘
   private static void CalTempContrib(int start, int stop) {
       double weight = 0;

       int i = 0;
       for (i = start; i <= stop; i++) {
           weight += contrib[i];
       }

       for (i = start; i <= stop; i++) {
           tmpContrib[i] = contrib[i] / weight;
       }

   } // end of CalTempContrib()

   private static int GetRedValue(int rgbValue) {
       int temp = rgbValue & 0x00ff0000;
       return temp >> 16;
   }

   private static int GetGreenValue(int rgbValue) {
       int temp = rgbValue & 0x0000ff00;
       return temp >> 8;
   }

   private static int GetBlueValue(int rgbValue) {
       return rgbValue & 0x000000ff;
   }

   private static int ComRGB(int redValue, int greenValue, int blueValue) {

       return (redValue << 16) + (greenValue << 8) + blueValue;
   }

   // 行水平滤波
   private static int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
           int start, int stop, int y, double[] pContrib) {
       double valueRed = 0.0;
       double valueGreen = 0.0;
       double valueBlue = 0.0;
       int valueRGB = 0;
       int i, j;

       for (i = startX, j = start; i <= stopX; i++, j++) {
           valueRGB = bufImg.getRGB(i, y);

           valueRed += GetRedValue(valueRGB) * pContrib[j];
           valueGreen += GetGreenValue(valueRGB) * pContrib[j];
           valueBlue += GetBlueValue(valueRGB) * pContrib[j];
       }

       valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
               Clip((int) valueBlue));
       return valueRGB;

   } // end of HorizontalFilter()

   // 图片水平滤波
   private static BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
       int dwInW = bufImage.getWidth();
       int dwInH = bufImage.getHeight();
       int value = 0;
       BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
               BufferedImage.TYPE_INT_RGB);

       for (int x = 0; x < iOutW; x++) {

           int startX;
           int start;
           int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
           int y = 0;

           startX = X - nHalfDots;
           if (startX < 0) {
               startX = 0;
               start = nHalfDots - X;
           } else {
               start = 0;
           }

           int stop;
           int stopX = X + nHalfDots;
           if (stopX > (dwInW - 1)) {
               stopX = dwInW - 1;
               stop = nHalfDots + (dwInW - 1 - X);
           } else {
               stop = nHalfDots * 2;
           }

           if (start > 0 || stop < nDots - 1) {
               CalTempContrib(start, stop);
               for (y = 0; y < dwInH; y++) {
                   value = HorizontalFilter(bufImage, startX, stopX, start,
                           stop, y, tmpContrib);
                   pbOut.setRGB(x, y, value);
               }
           } else {
               for (y = 0; y < dwInH; y++) {
                   value = HorizontalFilter(bufImage, startX, stopX, start,
                           stop, y, normContrib);
                   pbOut.setRGB(x, y, value);
               }
           }
       }

       return pbOut;

   } // end of HorizontalFiltering()

   private static int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
           int start, int stop, int x, double[] pContrib) {
       double valueRed = 0.0;
       double valueGreen = 0.0;
       double valueBlue = 0.0;
       int valueRGB = 0;
       int i, j;

       for (i = startY, j = start; i <= stopY; i++, j++) {
           valueRGB = pbInImage.getRGB(x, i);

           valueRed += GetRedValue(valueRGB) * pContrib[j];
           valueGreen += GetGreenValue(valueRGB) * pContrib[j];
           valueBlue += GetBlueValue(valueRGB) * pContrib[j];
           // System.out.println(valueRed+"->"+Clip((int)valueRed)+"<-");
           // 
           // System.out.println(valueGreen+"->"+Clip((int)valueGreen)+"<-");
           // System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"<-"+"-->");
       }

       valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
               Clip((int) valueBlue));
       // System.out.println(valueRGB);
       return valueRGB;

   } // end of VerticalFilter()

   private static BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
       int iW = pbImage.getWidth();
       int iH = pbImage.getHeight();
       int value = 0;
       BufferedImage pbOut = new BufferedImage(iW, iOutH,
               BufferedImage.TYPE_INT_RGB);

       for (int y = 0; y < iOutH; y++) {

           int startY;
           int start;
           int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);

           startY = Y - nHalfDots;
           if (startY < 0) {
               startY = 0;
               start = nHalfDots - Y;
           } else {
               start = 0;
           }

           int stop;
           int stopY = Y + nHalfDots;
           if (stopY > (int) (iH - 1)) {
               stopY = iH - 1;
               stop = nHalfDots + (iH - 1 - Y);
           } else {
               stop = nHalfDots * 2;
           }

           if (start > 0 || stop < nDots - 1) {
               CalTempContrib(start, stop);
               for (int x = 0; x < iW; x++) {
                   value = VerticalFilter(pbImage, startY, stopY, start, stop,
                           x, tmpContrib);
                   pbOut.setRGB(x, y, value);
               }
           } else {
               for (int x = 0; x < iW; x++) {
                   value = VerticalFilter(pbImage, startY, stopY, start, stop,
                           x, normContrib);
                   pbOut.setRGB(x, y, value);
               }
           }

       }

       return pbOut;

   } // end of VerticalFiltering()

   static int Clip(int x) {
       if (x < 0)
           return 0;
       if (x > 255)
           return 255;
       return x;
   }
   
   /**
    * 根据原图片名，获得多种尺寸的图片
    * 说明：
    * 1、此方法与图片裁剪配合使用；
    * 2、图片裁剪时，文件存有多种尺寸，分别是：C、XXL、XL、L、M、S
    * 3、但数据库中只存原始路径，因此需要转换得到相应裁剪后的图片路劲
    * @param srcUrl
    */
   public static String getImageUrl(String srcUrl, String sizeCode){
	   // 得到文件名
	   String fileName = srcUrl.substring(0, srcUrl.indexOf("."));
	   // 得到文件的后缀名
	   String fileExt = srcUrl.substring(srcUrl.indexOf("."));
	   String newFileName = fileName + "_" + sizeCode + fileExt;
	   return newFileName;
   }
}
